package com.cskaoyan.servlet;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.GoodsUpdateVo;
import com.cskaoyan.bean.vo.GoodsVo;
import com.cskaoyan.bean.vo.MarketCategoryValue;
import com.cskaoyan.bean.vo.catAndBrandVo;
import com.cskaoyan.service.*;
import com.cskaoyan.util.JacksonUtil;
import com.cskaoyan.util.ResponseUtil;
import com.cskaoyan.util.TransactionUtil;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author Ramsey
 * @date 2023年05月30日 13:40
 */
@WebServlet("/admin/goods/*")
public class AdminGoodsServlet extends WdBaseServlet {

    private GoodsService goodsService = new GoodsServiceimpl();
    private GoodsAttributeService attributeService = new GoodsAttributeServiceimpl();
    private GoodsSpecificationService specificationService = new GoodsSpecificationServiceimpl();
    private GoodsProductService productService = new GoodsProductServiceimpl();

    //显示列表用的
    private AdminBrandService brandService = new AdminBrandServiceimpl();
    private CategoryService categoryService = new CategoryServiceimpl();

    // 展示页面
    public BaseRespVo list(HttpServletRequest request, HttpServletResponse response) {
        // 1. 请求参数的接收

        Integer page = Integer.valueOf(request.getParameter("page"));
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");

        // 商品id  编号   名称
        // 错误的写法  ----Integer goodsId = Integer.valueOf(request.getParameter("goodsId"));

        String goodsId = request.getParameter("goodsId");
        String goodsSn = request.getParameter("goodsSn");
        String name = request.getParameter("name");
        CommonData data = goodsService.query(page, limit, sort, order, goodsId, goodsSn, name);

        return BaseRespVo.ok(data);
    }

    public BaseRespVo catAndBrand(HttpServletRequest request, HttpServletResponse response) {
        //
        System.out.println("进入catAndBrand");
        //先找品牌对应的key-value
        List<Map> brandList = brandService.selectByMap();//成功
        //再来单表复合查询
        List<MarketCategoryValue> marketCategoryValues = categoryService.selectByMap();
        catAndBrandVo catAndBrandVo = new catAndBrandVo(brandList, marketCategoryValues);//返回本质是两个集合
        return BaseRespVo.ok(catAndBrandVo);
    }

    @SneakyThrows
    public BaseRespVo create(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("--------------------进入创建商品页面------------------------------");
        String jsonStr = request.getReader().readLine();
        System.out.println("json转换" + jsonStr);
        GoodsVo goodsVo = JacksonUtil.read(jsonStr, GoodsVo.class);
        TransactionUtil.startTransaction();
        try {
            BaseRespVo error = validate(goodsVo);
            if (error == null) {
                return error;
            }

            MarketGoods goods = goodsVo.getGoods();
            MarketGoodsAttribute[] attributes = goodsVo.getAttributes();
            MarketGoodsSpecification[] specifications = goodsVo.getSpecifications();
            MarketGoodsProduct[] products = goodsVo.getProducts();

            String name = goods.getName();
            if (this.checkExistByName(name)) {
                return BaseRespVo.fail(611, "商品名已经存在");
            }

            // 商品表里面有一个字段retailPrice记录当前商品的最低价
            BigDecimal retailPrice = new BigDecimal(Integer.MAX_VALUE);
            for (MarketGoodsProduct product : products) {
                BigDecimal productPrice = product.getPrice();
                if (retailPrice.compareTo(productPrice) == 1) {
                    retailPrice = productPrice;
                }
            }
            goods.setRetailPrice(retailPrice);
            //设置更新时间和add时间做到回显
            java.util.Date updateTime = new Date();//获得当前时间
            goods.setAddTime(updateTime);
            goods.setUpdateTime(updateTime);
            // 商品基本信息表market_goods
            goodsService.add(goods);

            // 商品规格表market_goods_specification
            for (MarketGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setId(null);
                specificationService.add(specification);
            }

            // 商品参数表market_goods_attribute
            for (MarketGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());
                attribute.setId(null);
                attributeService.add(attribute);
            }

            // 商品货品表market_product
            for (MarketGoodsProduct product : products) {
                product.setId(null);
                product.setGoodsId(goods.getId());
                productService.add(product);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            TransactionUtil.rollback();
        }
        TransactionUtil.commit();
        return BaseRespVo.ok(goodsVo);
    }

    @SneakyThrows
    public BaseRespVo update(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("--------------------进入商品更新页面------------------------------");
        String jsonStr = request.getReader().readLine();
        System.out.println("json转换" + jsonStr);
        GoodsUpdateVo goodsVo = JacksonUtil.read(jsonStr, GoodsUpdateVo.class);

        MarketGoods goods = goodsVo.getGoods();
        MarketGoodsAttribute[] attributes = goodsVo.getAttributes();
        MarketGoodsSpecification[] specifications = goodsVo.getSpecifications();
        MarketGoodsProduct[] products = goodsVo.getProducts();

        // 商品表里面有一个字段retailPrice记录当前商品的最低价
        BigDecimal retailPrice = new BigDecimal(Integer.MAX_VALUE);
        for (MarketGoodsProduct product : products) {
            BigDecimal productPrice = product.getPrice();
            if (retailPrice.compareTo(productPrice) == 1) {
                retailPrice = productPrice;
            }
        }
        goods.setRetailPrice(retailPrice);

        //开始事务
        TransactionUtil.startTransaction();

        // 商品基本信息表market_goods
        goodsService.update(goods);

        //商品规格表market_goods_specification
        for (MarketGoodsSpecification specification : specifications) {
            specificationService.update(specification);
        }

        // 商品参数表market_goods_attribute
        for (MarketGoodsAttribute attribute : attributes) {
            attributeService.update(attribute);
        }
        // 商品货品表market_product
        for (MarketGoodsProduct product : products) {
            productService.updateByObject(product);
        }
        //提交事务
        TransactionUtil.commit();
        return BaseRespVo.ok();
    }


    // 删除market_goods表中的元素
    @SneakyThrows
    public BaseRespVo delete(HttpServletRequest request, HttpServletResponse response) {
        String jsonStr = request.getReader().readLine();
        MarketGoods marketGoods = JacksonUtil.read(jsonStr, MarketGoods.class);

        goodsService.delete(marketGoods.getId());

        return BaseRespVo.ok();
    }


    @SneakyThrows
    public BaseRespVo detail(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("--------------------进入显示商品详情页面------------------------------");
        //获取参数
        Integer id = Integer.valueOf(request.getParameter("id"));
        System.out.println(id);

        //开始事务
        TransactionUtil.startTransaction();

        MarketGoods goods = goodsService.selectById(id);
        //
        List<MarketGoodsAttribute> marketGoodsAttributes = attributeService.selectByGoodsId(id);
        MarketGoodsAttribute[] attributes = new MarketGoodsAttribute[marketGoodsAttributes.size()];
        marketGoodsAttributes.toArray(attributes);
        //
        List<MarketGoodsSpecification> specificationList = specificationService.selectByGoodsId(id);
        MarketGoodsSpecification[] spec = new MarketGoodsSpecification[specificationList.size()];
        specificationList.toArray(spec);

        //
        List<MarketGoodsProduct> list = productService.selectByGoodsId(id);
        MarketGoodsProduct[] products = new MarketGoodsProduct[list.size()];
        list.toArray(products);

        //categoryIds
        Integer categoryId = goods.getCategoryId();//二级条目(下面的操作如果没有找到一级的话那这个就是就是一级类目)
        List<MarketCategory> marketCategories = categoryService.selectById(categoryId);
        int[] categoryIds;//先声明
        if (marketCategories.size() > 0) {
            categoryIds = new int[marketCategories.size() + 1];//要么0要么1
            categoryIds[0] = marketCategories.get(0).getPid();//如果有pid放第一个
            categoryIds[1] = categoryId;
        } else {
            categoryIds = new int[1];//要么0要么1
            categoryIds[0] = categoryId;
        }
        //构造返回的
        GoodsVo goodsVo = new GoodsVo(categoryIds, goods, spec, attributes, products);//第一个多一个数组
        //提交事务
        TransactionUtil.commit();

        //TransactionUtil.startTransaction();

        // MarketGoods goods = goodsVo.getGoods();//找这三个东西
        // MarketGoodsAttribute[] attributes = goodsVo.getAttributes();
        // MarketGoodsSpecification[] specifications = goodsVo.getSpecifications();
        // MarketGoodsProduct[] products = goodsVo.getProducts();

        // Map<String, Object> map = new HashMap<>();
        // map.put("goods", goods);
        return BaseRespVo.ok(goodsVo);
    }


    private BaseRespVo validate(GoodsVo goodsVo) {
        if (goodsVo == null) {
            System.out.println("获取的goodsVo为空");
            return null;
        }
        return BaseRespVo.ok();
    }

    private boolean checkExistByName(String name) {
        //"商品名已经存在"
        System.out.println("检查商品名是否已经存在（这里省略了）");
        return false;
    }
}